<!-- 弹窗详情 

选中子节点时选中父节点
- 提交时：通过 getClanByList 获取选中的节点及其祖先节点
- 获取数据是：通过 getChoiceAllChild 获取所有选中了子节点的节点

-->
<template>
	<a-modal v-model:visible="_d.visible" :title="modalTitle" width="800px"
		:bodyStyle="{minHeight: '300px'}"
		@ok="handleOk">
  	<a-form :label-col="{style: {width: '6em'}}">
  		<a-row :gutter="20">
  			<a-col :span="14">
  				<a-form-item label="角色名称" v-bind="validateInfos.text">
		    		<a-input v-model:value="_d.form.text" placeholder="请输入"></a-input>
		    	</a-form-item>
		    	<a-form-item label="描述">
		    		<a-textarea v-model:value="_d.form.descript" placeholder="请输入"></a-textarea>
		    	</a-form-item>
		    	<a-form-item label="角色类型">
		    		<a-radio-group v-model:value="_d.form.type" name="typeGroup">
					    <a-radio v-for="(item, index) in _d.typeList" :key="index" :value="item.value">{{item.label}}</a-radio>
					  </a-radio-group>
		    	</a-form-item>
		    	<a-form-item label="排序">
		    		<a-input-number style="width: 100%;" v-model:value="_d.form.order" placeholder="请输入"></a-input-number>
		    	</a-form-item>
  			</a-col>
  			<a-col :span="10">
  				<div class="menu-tree">
  					<a-tree
					    v-model:checkedKeys="_d.form.menuIds"
					    checkable
					    :height="400"
					    :tree-data="_d.menuTree"
					    :fieldNames="{title: 'text', key: 'id'}">
					  </a-tree>
  				</div>
  			</a-col>
  		</a-row>
    </a-form>
  </a-modal>
</template>

<script setup>
	import { reactive, ref, computed, onMounted } from 'vue'
	import { Form, notification } from 'ant-design-vue';
	import MenuSelect from "@/components/Select/MenuSelect.vue";

	import { save, detail } from "@/api/role.js";
	import {RoleTypeEnum} from "@/api/emnu.js";
	import { tree } from "@/api/menu.js";

	const emit = defineEmits(['reload']);

	const _d = reactive({
		visible: false,

		id: '',
		detail: {},

		form: {
			text: '',
			descript: '',
			type: 'County',
			order: 1,
			menuIds: [],
		},

		rules: {
			text: [
				{ required: true, trigger: 'blur', message: '请输入角色名称' }
			],
		},

		// 列表
		typeList: [],

		// 当前选中值
		checkedKeys: ['111631985120876'],
		// 树形菜单
		menuTree: [],
		// 1维菜单
		menu1D: [],

	})

	// 验证
	const { resetFields, validate, validateInfos } = Form.useForm(_d.form, _d.rules);


	const modalTitle = computed(() => {
		return _d.id ? '编辑角色' : '添加角色';
	})

	onMounted(() => {
		getTypeList();
		getMenuTree();
	})

	function open(id = null) {
		_d.id = id;
		resetFields();

		getData();

		_d.visible = true;
	}

	// 获取角色列表
	function getTypeList() {
		RoleTypeEnum().then(res => {
			_d.typeList = res.map(item => {
				return {
					value: item.id,
					label: item.name
				}
			})
		})
	}

	// 获取树形菜单
	function getMenuTree() {
		tree().then(res => {
			_d.menuTree = res;
			_d.menu1D = recursion(res);
		})

		// 递归生成1维数据
		function recursion(list, pId = '') {
			let arr = [] ;
			for(let i = 0; i < list.length; i++) {
				let item = list[i];
				item.pId = pId;
				arr.push(item);
				if(item.children && item.children.length) {
					arr.push(...recursion(item.children, item.id));
				}
			}
			return arr;
		}
	}

	// 根据选中值，获取当前及祖先级值
	function getClanByList(list, tree) {
		const res = [];
		list.forEach(value => {
			let id = value;
			while(id) {
				let oItem = tree.find(item => item.id == id);
				res.push(oItem.id);
				id = oItem.pId;
			}
		})
		// 去重
		return [...new Set(res)];
	}

	// 获取选中所有子节点的节点，传入当前选中所有值，和1维数据
	function getChoiceAllChild(list, tree) {
		const res = [];
		list.forEach(value => {
			let oItem = tree.find(item => item.id == value);
			if(oItem.children && oItem.children.length) {
				if(oItem.children.every(aItem => {
					return list.find(bValue => aItem.id == bValue);
				})) {
					res.push(value);
				}
			} else {
				res.push(value);
			}
		})
		return res;
	}

	// 查看详情
	function getData() {
		if(!_d.id) {
			return;
		}
		let params = {
			roleId: _d.id
		}
		detail(params).then(res => {
			_d.form.text = res.roleName;
			_d.form.descript = res.descript;
			_d.form.type = res.roleType;
			_d.form.order = Number(res.orderNum);
			// 获取选中所有子节点的节点，传入当前选中所有值，和1维数据
			_d.form.menuIds = getChoiceAllChild(res.roleToMenus.split(','), _d.menu1D);
		})
	}


	// 提交
	function handleOk() {
		validate().then(() => {
			let params = {
				..._d.form
			}
			params.menuIds = getClanByList(params.menuIds, _d.menu1D).join(',');

			if(_d.id) {
				params.id = _d.id;
			}
			save(params).then(res => {
				if(res.code && res.code != 200) {
					notification.error({
						message: '提示',
						description: res.message
					})
					return;
				}
				notification.success({
					message: '提示',
					description: '保存成功'
				})
				_d.visible = false;
				emit('reload');
			})
		})
	}


	defineExpose({
		open
	})

</script>

<style lang="less" scoped>
.menu-tree {
	position: relative;
	padding: 10px;
	width: 100%;
	height: 423px;
	border: 1px solid #D9D9D9;
	&:before {
		content: '菜单列表';
		position: absolute;
		top: -12px;
		left: 20px;
		padding: 0 5px;
		background: #fff;
	}
}
</style>